﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HZH_Controls.Controls;
using Petroleum.UC.Public;
using Petroleum.DB.Model;
using Petroleum.Model;
using Newtonsoft.Json;
using System.Data.SQLite;
using Petroleum.Tool;
using HZH_Controls.Forms;

namespace Petroleum.UC
{
    public partial class Step6BHADesign : UserControl
    {
        FormMain main = new FormMain();

        /// <summary>
        /// 套管List
        /// </summary>
        List<Casing> casingList = Session.CasingProgram.CasingList;
        public List<BHA> BHAList = new List<BHA>();
        /// <summary>
        /// Step6
        /// </summary>
        public List<DrillingParameters> DrillingParametersList = new List<DrillingParameters>();
        /// <summary>
        /// 当前操作对象
        /// </summary>
        Casing casing = new Casing();
        Casing editcasing = new Casing();
        public Step6BHADesign(FormMain main)
        {
            InitializeComponent();
            ToolStripManager.Renderer = new ProfessionalToolStripRendererEx();
            spudImg1.Initialization("2nd Spud Torque");
            spudImg2.Initialization("2nd Spud Torque");
            this.main = main;
            Load();
        }
        new void Load()
        {
            List<KeyValuePair<string, string>> spudCom = casingList.Select(m =>
                new KeyValuePair<string, string>(m.CasingInterval, m.SpudNo)
            ).ToList();

            cmdCasing.Source = spudCom;
            cmdCasing.SelectedIndex = 0;
        }
        private void cmd_SelectedChangedEvent(object sender, EventArgs e)
        {
            //获取对应的套管
            string spud = cmdCasing.SelectedText;
            casing = casingList.FirstOrDefault(m => m.SpudNo == spud);
            if (casing != null)
            {
                labBS.Text = casing.BitSize;      //BitSize赋值
                labCS.Text = casing.CasingSize;      //CasingSize赋值
            }
        }
        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            this.verificationComponent1.Verification();
            if (lstErrorControl.Count == 0 && casing != null)
            {
                //casing = new Casing();
                casing.BHAName = txtBHAName.InputText;
                casing.BHANo = txtBHANo.InputText;
                casing.BHAList.Clear();
                for (int i = 0; i < dgvBHA.Rows.Count; i++)
                {
                    BHA bha = new BHA()
                    {
                        ComponentsName = GetCellString(dgvBHA, i, "ComponentsName"),
                        Mount = GetCellString(dgvBHA, i, "Mount"),
                        Size = GetCellString(dgvBHA, i, "BHASize"),
                        No = i,
                    };
                    if (!string.IsNullOrEmpty(bha.ComponentsName))
                        casing.BHAList.Add(bha);
                }
                casing.DrillingParametersList.Clear();
                for (int i = 0; i < dgvDP.Rows.Count; i++)
                {
                    DrillingParameters dp = new DrillingParameters()
                    {
                        FlowRate = GetCellString(dgvDP, i, "FlowRatel"),
                        PumpPressureMPa = GetCellString(dgvDP, i, "RPMr"),
                        RPM = GetCellString(dgvDP, i, "PumpPressureMPa"),
                        WOBkN = GetCellString(dgvDP, i, "WOB")
                    };
                    if (!string.IsNullOrEmpty(dp.WOBkN))
                        casing.DrillingParametersList.Add(dp);
                }
                if (editcasing != null && !string.IsNullOrEmpty(editcasing.SpudNo))
                {
                    casingList.Remove(editcasing);
                    casingList.Add(casing);
                }
                dgv.DataSource = casingList;
                FrmTips.ShowTipsSuccess(new FormMain(), "已保存");
            }
            lstErrorControl.Clear();
            this.Invalidate(true);
        }
        string GetCellString(DataGridView data, int RowIndex, string CellName)
        {
            if (data.Rows[RowIndex].Cells[CellName].Value != null)
            {
                string value = data.Rows[RowIndex].Cells[CellName].Value.ToString();
                return value;
            }
            return "";
        }
        private void dgv_Load(object sender, EventArgs e)
        {
            List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "SpudNo", HeadText = "SpudNo", Width = 200, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CasingInterval", HeadText = "CasingInterval", Width = 200, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "BHAName", HeadText = "BHAName", Width = 200, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "BHANo", HeadText = "BHANo", Width = 200, WidthType = SizeType.Absolute });
            //lstCulumns.Add(new DataGridViewColumnEntity() { Width = 300, WidthType = SizeType.Absolute, CustomCellType = typeof(Step6_Button) });
            dgv.RowHeight = 50;
            this.dgv.Columns = lstCulumns;
            this.dgv.DataSource = casingList;
        }
        void SaveData()
        {
            Session.CasingProgram.CasingList = casingList;
            Session.CasingProgram.spudImg1 = spudImg1.ImgUrl;
            Session.CasingProgram.spudImg2 = spudImg2.ImgUrl;
        }
        private void btnUp_BtnClick(object sender, EventArgs e)
        {
            main.AddControl(new StepADrillingTeamSelect(main));
        }
        private void btnDown_BtnClick(object sender, EventArgs e)
        {
            SaveData();
            main.AddControl(new Step7(main));
        }
        List<Control> lstErrorControl = new List<Control>();
        private void verificationComponent1_Verificationed(VerificationEventArgs e)
        {
            if (!e.IsVerifySuccess)
            {
                lstErrorControl.Add(e.VerificationControl);
            }
        }
        #region 保存
        private void btnword_BtnClick(object sender, EventArgs e)
        {
            try
            {
                var casing = main.projects.Where(n => n.TableName == TableNames.CasingProgram.ToString()).FirstOrDefault();
                if (casing != null)
                {
                    Session.CasingProgram = JsonConvert.DeserializeObject<CasingProgram>(casing.TableData);
                    casingList = Session.CasingProgram.CasingList;
                    dgv.DataSource = casingList;
                    if (!string.IsNullOrEmpty(Session.CasingProgram.spudImg1))
                        spudImg1.picImg.Image = Image.FromFile(Session.CasingProgram.spudImg1);
                    if (!string.IsNullOrEmpty(Session.CasingProgram.spudImg2))
                        spudImg1.picImg.Image = Image.FromFile(Session.CasingProgram.spudImg2);
                }
            }
            catch (Exception ex)
            {

            }
        }
        private void btnsave_BtnClick(object sender, EventArgs e)
        {
            SaveData();
            SQLiteDataReader reader = main.sqliteHelper.ReadFullTable("SessionData");
            var projects = EntityTranslate.Translate<SessionData>(reader);
            var FormationPressure = projects.Where(n => n.TableName == TableNames.CasingProgram.ToString()).FirstOrDefault();
            if (FormationPressure != null)
                SQLiteHelper.SaveData(main.sqliteHelper, TableNames.CasingProgram.ToString(), JsonConvert.SerializeObject(Session.CasingProgram));
            else
                SQLiteHelper.SaveData(main.sqliteHelper, TableNames.CasingProgram.ToString(), JsonConvert.SerializeObject(Session.CasingProgram), 1);
            FrmTips.ShowTipsSuccess(new FormMain(), "数据保存成功！");
        }
        #endregion
        #region 复制数据、
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //在检测到按Ctrl+V键后，系统无法复制多单元格数据，重写ProcessCmdKey方法，屏蔽系统粘贴事件，使用自定义粘贴事件，在事件中对剪贴板的HTML格式进行处理，获取表数据，更新DataGrid控件内容
            if (keyData == (Keys.V | Keys.Control))
            {
                if (this.dgvBHA.SelectedCells.Count > 0 && this.dgvBHA.Focused)
                    DGVHelper.CopyData(this.dgvBHA);
                if (this.dgvDP.SelectedCells.Count > 0 && this.dgvDP.Focused)
                    DGVHelper.CopyData(this.dgvDP);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion
        private void StripMenuDel_Click(object sender, EventArgs e)
        {
            if (dgvBHA.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow item in dgvBHA.SelectedRows)
                {
                    if (!item.IsNewRow)
                        dgvBHA.Rows.Remove(item);
                }
                return;
            }
            FrmTips.ShowTipsWarning(this.FindForm(), "请先选择要删除的行");
        }
        private void StripMenuDeldgvDP_Click(object sender, EventArgs e)
        {
            if (dgvDP.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow item in dgvDP.SelectedRows)
                {
                    if (!item.IsNewRow)
                        dgvDP.Rows.Remove(item);
                }
                return;
            }
            FrmTips.ShowTipsWarning(this.FindForm(), "请先选择要删除的行");
        }
        private void itemdel_Click(object sender, EventArgs e)
        {
            if (dgv.SelectRow != null)
            {
                int row = dgv.SelectRow.RowIndex;
                if (row > -1)
                {
                    casingList.RemoveAt(row);
                    this.dgv.DataSource = casingList;
                    return;
                }
            }
            FrmTips.ShowTipsWarning(this.FindForm(), "请先选择要删除的行");
        }
        private void itemedit_Click(object sender, EventArgs e)
        {
            if (dgv.SelectRow != null)
            {
                int row = dgv.SelectRow.RowIndex;
                editcasing = casingList[row];
                cmdCasing.SelectedValue = editcasing.CasingInterval;
                txtBHANo.InputText = editcasing.BHANo;
                txtBHAName.InputText = editcasing.BHAName;
                AddRow(editcasing.BHAList);
                AddRow(editcasing.DrillingParametersList);
            }
        }
        void AddRow(List<BHA> list)
        {
            dgvBHA.Rows.Clear();
            foreach (var p in list)
            {
                int index = this.dgvBHA.Rows.Add();
                this.dgvBHA.Rows[index].Cells[0].Value = p.ComponentsName;
                this.dgvBHA.Rows[index].Cells[1].Value = p.Size;
                this.dgvBHA.Rows[index].Cells[2].Value = p.Mount;
            }
        }
        void AddRow(List<DrillingParameters> list)
        {
            dgvDP.Rows.Clear();
            foreach (var p in list)
            {
                int index = this.dgvDP.Rows.Add();
                this.dgvDP.Rows[index].Cells[0].Value = p.WOBkN;
                this.dgvDP.Rows[index].Cells[1].Value = p.RPM;
                this.dgvDP.Rows[index].Cells[2].Value = p.FlowRate;
                this.dgvDP.Rows[index].Cells[3].Value = p.PumpPressureMPa;
            }
        }
    }
}
